/**
 * LayChat云服务
 * laychat.workerman.net
 */

var WEB_SOCKET_SWF_LOCATION = "./static/swf/WebSocketMain.swf";
var WEB_SOCKET_DEBUG = true;
var WEB_SOCKET_SUPPRESS_CROSS_DOMAIN_SWF_ERROR = true;

var laychat = {
    appName: 'LayChat',
    initUrl: '/index.php/Home/swoole/init',
    // 初始化好友列表和群组接口，这个接口返回个json，格式见
    sendMessageUrl: '/index.php/Home/swoole/send_message',
    // 发消息接口
    membersUrl: '/index.php/Home/swoole/members.php',
    uploadImageUrl: '/index.php/Home/swoole/ajax_upload_img',
    uploadFileUrl: '/index.php/Home/swoole/upload_file.php',
    chatLogUrl: '/index.php/Home/swoole/chat_log',
    bindUrl: '/index.php/Home/swoole/bind',
    updateSignUrl: '/index.php/Home/swoole/ajax_update_sign',
    msgBoxUrl: '/index.php/Home/swoole/msg_box',
    agreeUrl: '/index.php/Home/swoole/agree',
    getNoticeUrl: '/index.php/Home/swoole/get_notice',
    changeStatusUrl: '/index.php/Home/swoole/ajax_change_status',
    // address           : 'ws://'+document.domain+':8282',
    address: 'ws://pdosgk.com:8282',
    setMin: false,
    findUrl: '/index.php/Home/swoole/find_friend',
    userInfo: null,
    inited: false,
    socket: null,
    jq: null,
    open: function() {
        if (this.isIE6or7()) return;
        if (!this.jq) this.jq = $;
        this.connectWorkerman();
    },
    isIE6or7: function() {
        var b = document.createElement('b');
        b.innerHTML = '<!--[if IE 5]><i></i><![endif]--><!--[if IE 6]><i></i><![endif]--><!--[if IE 7]><i></i><![endif]-->';
        return b.getElementsByTagName('i').length === 1;
    },
    connectWorkerman: function() {
        laychat.socket = new WebSocket(laychat.address);
        laychat.socket.onopen = function() {
            laychat.socket.send(JSON.stringify({
                type: 'init'
            }));
        };

        laychat.socket.onmessage = function(e) {
            var msg = JSON.parse(e.data);
            console.log(msg);
            // 如果layim还没有初始化就收到消息则忽略（init消息除外）
            if (!msg.message_type || (msg.message_type != 'init' && !layui.layim)) return;
            switch (msg.message_type) {
                // 初始化im
            case 'init':
                laychat.jq.post(laychat.bindUrl, {
                    client_id: msg.client_id
                }, function(data) {
                    if (data.code == 0) {
                        //创建在线用户列表
                        data.online_list = msg.online_list;
                        laychat.initIM(data);
                        //通知其他用户，上线通知
                        laychat.socket.send(JSON.stringify({
                            type: 'online',
                            'userInfo': data.userInfo
                        }));
                    } else {
                        alert('laychat服务端返回失败：' + data.msg);
                    }
                }, 'json');
                return;
                //新用户上线
            case 'newUser':
                layui.layim.addList(msg.userInfo);
                return;
                // 添加一个用户到好友列表
            case 'addList':
                if (laychat.jq('#layim-friend' + msg.data.id).length == 0 && laychat.userInfo && laychat.userInfo['id'] != msg.data.id) {
                    return layui.layim.addList(msg.data);
                }
                if (msg.data.type == 'friend') {
                    layui.layim.setFriendStatus(msg.data.id, 'online');
                }
                return;
                // 收到一个消息
            case 'chatMessage':
                console.log(layui.layim.cache().friend)
                if (msg.data.type == 'group') {
                    if (msg.data.from_id != laychat.userInfo.id) {
                        layui.layim.getMessage(msg.data);
                    }
                } else if (laychat.userInfo.id != msg.data.id) {
                    layui.layim.getMessage(msg.data);
                }
                return;
            case 'msgbox':
                // layui.layim.msgbox(++msgbox_count);
                layui.layim.msgbox('新');
                return;
                //好友同意添加好友
            case 'agree_friend':
                var user_info = msg.from_user;
                //移除在线好友列表
                layui.layim.removeList({
                    type: 'friend' //或者group
                    ,
                    id: user_info.id //好友或者群组ID
                });
                console.log(msg);
                //把该好友添加到好友列表
                layui.layim.addList({
                    type: 'friend' //列表类型，只支持friend和group两种
                    ,
                    avatar: user_info.avatar //好友头像
                    ,
                    username: user_info.username //好友昵称
                    ,
                    groupid: msg.groupid //所在的分组id
                    ,
                    id: user_info.id //好友id
                    ,
                    sign: user_info.sign //好友签名
                });
                layui.layim.msgbox('新');
                return;
                //拒绝添加好友
            case 'refuse_friend':
                layui.layim.msgbox('新');
                return;
                // 退出
            case 'inputting':
                //如果有打开该好友窗口， 则显示正在输入状态
                var friend_chat_class = "layim-chatlist-friend"+msg.from_user;
                
                if($(".layim-chat-list .layim-this").hasClass(friend_chat_class)){
                    layui.layim.setChatStatus('<span style="color:#FF5722;">对方正在输入。。。</span>');
                    setTimeout(function(){
                        layui.layim.setChatStatus('');
                    },1000)
                }
                console.log(msg);
                return;
            case 'logout':
                // 隐身
            case 'hide':
                return layui.layim.setFriendStatus(msg.id, 'offline');
                // 上线
            case 'online':
                if (laychat.jq('.layim-list-friend .layim-friend' + msg.userid).length == 0 && laychat.userInfo && laychat.userInfo['id'] != msg.userid) {
                    return layui.layim.addList(msg.userInfo);
                } else return layui.layim.setFriendStatus(msg.userid, 'online');
            }
        }
        laychat.socket.onclose = laychat.connectWorkerman;
    },
    sendHeartbeat: function() {
        if (this.socket && this.socket.readyState == 1) {
            this.socket.send(JSON.stringify({
                type: 'ping'
            }));
        }
    },
    initIM: function(data) {
        var unread_msg_tips = function(data) {
                // 离线消息
                for (var key in data.unread_message) {
                    layui.layim.getMessage(JSON.parse(data.unread_message[key]));
                }
                if (data.unread_notice_count) {
                    // 设置消息盒子未读计数
                    layui.layim.msgbox(data.unread_notice_count);
                }
                return;
            };
        // layim已经初始化了，则只提示未读消息
        if (this.inited) {
            return unread_msg_tips(data);
        }
        this.inited = true;
        // 心跳数据，用来保持长链接，避免socket链接长时间不通讯被路由节点防火墙关闭
        setInterval('laychat.sendHeartbeat()', 12000);
        layui.use('layim', function(layim) {
            layim.config({
                //初始化接口
                init: {
                    url: laychat.initUrl + (laychat.initUrl.indexOf('?') == -1 ? '?' : '&') + 'online_list=' + data.online_list
                }

                //查看群员接口
                ,
                members: {
                    url: laychat.membersUrl
                }

                // 上传图片
                ,
                uploadImage: {
                    url: laychat.uploadImageUrl
                }

                // 上传文件
                ,
                uploadFile: {
                    url: laychat.uploadFileUrl
                },
                tool: [{
                    alias: 'code',
                    title: '代码',
                    icon: '&#xe64e;'
                }]

                ,
                msgbox: laychat.msgBoxUrl + (laychat.msgBoxUrl.indexOf('?') == -1 ? '?' : '&') + 'getNoticeUrl=' + encodeURI(laychat.getNoticeUrl) + '&agreeUrl=' + encodeURI(laychat.agreeUrl),
                initSkin: '3.jpg' //1-5 设置初始背景
                //聊天记录地址
                ,
                chatLog: laychat.chatLogUrl

                ,
                find: laychat.findUrl

                ,
                copyright: false //是否授权

                ,
                title: laychat.appName

                ,
                min: laychat.setMin
            });

            //监听发送消息
            layim.on('sendMessage', function(data) {
                laychat.jq.post(laychat.sendMessageUrl, {
                    data: data
                }, function(data) {
                    if (data.code != 0) {
                        layui.layer.msg(data.msg, {
                            time: 7000
                        });
                    }
                }, 'json');
                //发送消息倒Socket服务
                laychat.socket.send(JSON.stringify({
                    "type": "chatMessage",
                    "data": data
                }));
            });

            //监听在线状态的切换事件
            layim.on('online', function(data) {
                // laychat.jq.post(laychat.changeStatusUrl, { data: data} , function(data){
                //     if(data.code != 0) {
                //         layui.layer.msg(data.msg, {time: 7000});
                //     }
                // }, 'json');
                laychat.socket.send(JSON.stringify({
                    type: data
                }));
            });

            //更改个性签名
            layim.on('sign', function(value) {
                laychat.jq.post(laychat.updateSignUrl, {
                    sign: value
                }, function(data) {
                    if (data.code != 0) {
                        layui.layer.msg(data.msg, {
                            time: 7000
                        });
                    }
                }, 'json');
            });

            //layim建立就绪
            layim.on('ready', function(res) {
                laychat.userInfo = layim.cache().mine;
                // 离线消息
                return unread_msg_tips(data);
            });
        });
        //监控输入框, 有修改发送修改状态到对方
        $("body").on("keyup", ".layim-chat-textarea" ,function (i) {
            var val=$(".layim-chat-list .layim-this").attr("class");//这里获取class值
            var array=val.split(" ");//split双引号里面是空格，把class值用空格分开，转换为数组
            var to_userid = array[0].substr(21);
            laychat.socket.send(JSON.stringify({
                type     : 'inputting',
                from_user:laychat.userInfo['id'],
                to_userid:to_userid
            }));
        })
    },
    addGroup: function(data){
        //添加到缓存中
        var groupCount = layui.layim.cache().friend.length - 1;
        console.log(groupCount);
        layui.layim.cache().friend.splice(groupCount,0,data);
        var html = '<li><h5 layim-event="spread" lay-type="false"><i class="layui-icon"></i><span>'+data.groupname+'</span><em>(<cite class="layim-count"> 0</cite>)</em></h5><ul class="layui-layim-list"><li class="layim-null">该分组下暂无好友</li></ul></li>';
        $(".layim-list-friend > li").eq(groupCount-1).after(html)
    }
};